package forum.service;

import forum.DBConnectie;
import forum.Filter;
import forum.Variable;
import forum.wrapper.WrapRequest;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: Ivan
 * Date: 2010-7-8
 * Time: 15:35:39
 */
public class Thread {
     DBConnectie db = new DBConnectie(Variable.getDb(), Variable.getDbLogin(), Variable.getDbPassword());

    public String add(WrapRequest request) throws Exception{

            String forum_id = request.getParameter("forum_id");
            int lastThread_id = Integer.parseInt(request.getParameter("lastThread_id"));
            String thread_id = Integer.toString(lastThread_id + 1);

            String title = request.getParameter("title");


            if (title.equals("")) {
                title = "No title";
            } else {
                title = Filter.filterAll(title);
            }

            String message = request.getParameter("message");
            message = Filter.filterAll(message);
            String user = request.getParameter("user");

            db.connect();

            db.query(
                    "INSERT INTO forum_threads(forum_id,thread_id,title) " +
                            "VALUES(\"" + forum_id +
                            "\",\"" + thread_id +
                            "\",\"" + title + "\")");

            db.query(
                    "INSERT INTO forum_message(forum_id,thread_id,reply_id,message,user,date_time) " +
                            "VALUES(\"" + forum_id +
                            "\",\"" + thread_id +
                            "\",\"0" +
                            "\",\"" + message +
                            "\",\"" + user +
                            "\",SYSDATE())");

            db.close();

            return "index.jsp?page=thread&forum_id=" + forum_id;
    }

    public String delete(WrapRequest request) throws Exception{

            HttpSession session = request.getSession(true);
            String sessionType = (String) session.getAttribute("type");
            String forum_id = request.getParameter("forum_id");
            String thread_id = request.getParameter("thread_id");

            if (sessionType.equals("Admin")) {

                db.connect();

                db.query("DELETE FROM forum_message WHERE forum_id=\"" + forum_id + "\" AND thread_id=\"" + thread_id + "\"");
                db.query("DELETE FROM forum_threads WHERE forum_id=\"" + forum_id + "\" AND thread_id=\"" + thread_id + "\"");

                db.close();
            }

            return  "index.jsp?page=thread&forum_id=" + forum_id;
    }
}
